<template>
  <el-dialog
    v-model="show"
    @close="close"
    width="800px"
    title="编辑"
    style="text-align: center"
    align-center
  >
    <el-form ref="formRef" label-width="80" class="box">
      <div class="change-img">
        <span class="text">头像</span>
        <div class="upload">
          <el-upload
            class="avatar-uploader"
            :show-file-list="false"
            :auto-upload="false"
            @change="uploadImg"
          >
            <img v-if="user.headImg" :src="user.headImg" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </div>
      </div>
      <div
        :class="['inp', { bigInp: isBigInp(keyNameList[item]) }]"
        v-for="(item, index) in keys"
        :key="index"
      >
        <span class="text">{{ keyNameList[item] }}</span>
        <div class="put">
          <!-- 下拉框:角色选框 -->
          <el-select
            v-if="keyNameList[item] === '角色'"
            v-model="user[item]"
            class="role"
            placeholder="请选择角色"
            size="large"
            multiple
          >
            <el-option
              v-for="(item, index) in roleList"
              :key="index"
              :label="item"
              :value="item"
            />
          </el-select>
          <!-- 文本域:备注 -->
          <el-input
            type="textarea"
            v-else-if="keyNameList[item] === '备注'"
            v-model="user[item]"
            :placeholder="`请填写${keyNameList[item]}`"
          ></el-input>
          <!-- 单选框:状态 -->
          <el-radio-group
            v-model="user[item]"
            v-else-if="keyNameList[item] === '状态'"
            style="text-align: left; display: block"
          >
            <el-radio :label="1" size="large">开启</el-radio>
            <el-radio :label="0" size="large">关闭</el-radio>
          </el-radio-group>
          <!-- 输入框 -->
          <el-input
            v-model="user[item]"
            v-else
            :placeholder="`请填写${keyNameList[item]}`"
          ></el-input>
        </div>
      </div>
    </el-form>

    <div class="btn">
      <el-button type="default" @click="cancel">取消</el-button>
      <el-button type="success" @click="confirm">保存</el-button>
    </div>
  </el-dialog>
</template>

<script setup lang="ts">
import { reactive, ref, watch } from "vue"
import { uploadApi, addUserApi, updateUserApi } from "@/api"

// 引入上传图片相关图标
import { Plus } from "@element-plus/icons-vue"
import { ElMessage } from "element-plus"

// 自定义事件,接收外部控制弹出层显示隐藏双向绑定的数据
const emits = defineEmits(["update:showDig","reflesh"])

const props = defineProps<{
  showDig: boolean
  userInfo?: userType
}>()

// 列名-列显示名 映射表
const keyNameList: any = reactive({
  username: "用户名",
  name: "姓名",
  nickName: "昵称",
  password: "密码",
  roleName: "角色",
  email: "邮箱",
  phone: "手机号",
  remark: "备注",
  status: "状态"
})

// 角色列表
const roleList = ref(["系统管理员", "游客", "开发", "测试"])

// 转化为key
const keys = Object.keys(keyNameList)

// 用户的值
let user: any = ref({
  id: "",
  name: "",
  nickName: "",
  headImg: "",
  email: "",
  remark: "",
  status: 0,
  createTime: "",
  updateTime: "",
  username: "",
  phone: "",
  departmentId: "",
  roleName: [],
  departmentName: ""
})

function getUserInfo() {
  // 如果父组件有传值,需要拿到父组件的传值,渲染在用户信息上
  user.value = { ...props.userInfo }
  user.value.roleName = props.userInfo?.roleName?.split(",")
  user.value.status = props.userInfo?.status ? 1 : 0
}

// 弹出层的显示和隐藏
const show = ref(false)

// 新增还是编辑 - 0:新增 1:
const type = ref(0)

// 监听外部传入控制弹出层显示关闭的变量,由此控制弹出层显示隐藏
watch(
  () => props.showDig,
  () => {
    show.value = props.showDig
    if (props.userInfo && show.value) {
      // 有传参说明是新增
      getUserInfo()
      type.value = 1
    } else {
      user.value = {
        id: 0,
        name: "",
        nickName: "",
        headImg: "",
        email: "",
        remark: "",
        status: 0,
        username: "",
        phone: "",
        departmentId: "1",
        roleName: [],
        departmentName: ""
      }
      type.value = 0
    }
  }
)

// 函数判断哪个表单项占一整行
function isBigInp(bigInp: string): boolean {
  return ["角色", "备注", "状态"].includes(bigInp)
}

// 监听弹窗关闭事件, 改变父组件的控制变量
function close() {
  emits("update:showDig", false)
}

// 上传图片
async function uploadImg(file: any) {
  // 文件file
  const res = await uploadApi(file)
  user.value.headImg = res
}

// 取消
function cancel() {
  emits("update:showDig", false)
}

// 编辑
async function confirm() {
  // 转化一下角色数组
  // 角色映射表
  const obj : any = {
    "系统管理员": 10,
    "游客": 11,
    "开发": 12,
    "测试": 13
  }

  user.value.roleIdList = user.value.roleName.map((res:any)=>{
    return obj[res]
  })

  // 判断是编辑还是新增,0-新增 1-编辑
  if (type.value) {
    await updateUserApi(user.value)
    ElMessage({
      showClose: true,
      message: "更新成功",
      type: "success"
    })
  } else {
    await addUserApi(user.value)
    ElMessage({
      showClose: true,
      message: "新增成功",
      type: "success"
    })
  }

  // 告诉父组件关闭弹窗
  emits("update:showDig", false)

  // 告诉父组件刷新列表
  emits("reflesh")

}
</script>

<style lang="scss" scoped>
:deep(.el-dialog) {
  margin: 0 !important;
}

.box {
  display: flex;
  flex-wrap: wrap;
  padding-left: 30px;
}

.text {
  width: 50px;
  text-align: right;
  padding-right: 10px;
}

.change-img {
  width: 100%;
  height: 115px;
  display: flex;
  line-height: 30px;
  overflow: hidden;
  margin-bottom: 10px;

  img {
    object-fit: cover;
  }

  .upload {
    flex: 1;
    overflow: hidden;
    :deep(.avatar-uploader) {
      $w: 100px;
      width: $w;
      height: $w;
      display: block;
      border: 1px dashed #dcdfe6;
      display: flex;
      align-items: center;
      justify-content: center;
      border-radius: 10px;
      .el-upload {
        border: 1px dashed var(--el-border-color);
        width: 100%;
        height: 100%;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
        &:hover {
          border-color: var(--el-color-primary);
        }
      }
      .avatar {
        width: $w;
        height: $w;
        display: block;
      }
    }
  }
}

.inp {
  width: 50%;
  display: flex;
  align-items: center;
  box-sizing: border-box;
  overflow: hidden;
  padding: {
    bottom: 20px;
    right: 20px;
  }
  overflow: hidden;
  .put {
    flex: 1;
    :deep(.el-input__inner) {
      width: 100%;
    }
  }

  .role {
    width: 100%;
  }
}

.btn {
  display: flex;
  justify-content: flex-end;
}

.bigInp {
  width: 100%;
  display: flex;
}
</style>
